package cs304.p3.library.controller;

import java.sql.SQLException;
import java.util.Map;

import javax.swing.JOptionPane;

import com.google.common.collect.Maps;

import cs304.p3.library.dao.DevDao;
import cs304.p3.library.framework.IoC;
import cs304.p3.library.model.DBObjectForm;
import cs304.p3.library.model.DBTableModel.TableType;

public class DBObjectController extends Controller{
	
	private DBObjectForm dboForm = new DBObjectForm();
	
	public DBObjectForm getDBObjectForm(){
		return dboForm;
	}
	
	public void performAction(){
		DevDao devDao = IoC.resolve(DevDao.class);
		try {
			String[] args = dboForm.getArgs();
			TableType tableType = dboForm.getTableType();
			switch(dboForm.getActionType()){
			case INSERT:
				devDao.insert(tableType, args);
				break;
			case UPDATE:
				break;
			case DELETE:
				Map<String, String> argmap = Maps.newHashMap();
				String[] labels = tableType.getLabels();
				for(int i=0; i<args.length; i++){
					argmap.put(labels[i], args[i]);
				}
				devDao.delete(tableType, argmap);
				break;
			}
		} catch (SQLException e) {
			System.err.println("DEVDAO exception");
			JOptionPane.showMessageDialog(null, e.toString(), "DevDao Error", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}
	}

	@Override
	public void cleanUp() {
		dboForm = new DBObjectForm();
	}

}
